const router = require("koa-router")();
const { sequelize,Sequelize } = require("../common/dbs");
// var Sequelize = require("sequelize");
var Op = Sequelize.Op;

const articleModel = require("../models/article");
const articleInfo = articleModel(sequelize);

const classifyModel = require("../models/classify");
const classifyInfo = classifyModel(sequelize);

const userModel = require("../models/userinfo");
const userinfo = userModel(sequelize);

const { getUserId,getImgUrl } = require("../common/utils");

// 建立关系
articleInfo.hasOne(classifyInfo, { foreignKey: "id", sourceKey: "c_id" });
articleInfo.hasOne(userinfo, { foreignKey: "id", sourceKey: "u_id" });

// 查詢列表
const fnGetArticleList = async (aWhere = {}, reqQuery = {}) => {
  try {
    // 有数据
    let where = Object.assign({}, aWhere);

    let reData = await articleInfo.findAndCountAll({
      where: where,
      attributes: [
        "id",
        [Sequelize.col("userinfo_model.user_name"), "userName"],
        [Sequelize.col("classify_model.name"), "classifyName"],
        "u_id",
        "cover",
        "status",
        "title",
        "views",
        "desc",
        "created_at",
        "updated_at",
      ],
      order: [
        //排序 DESC ASC
        ["created_at", "DESC"],
      ],
      limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
      offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
      raw: true,
      include: [
        {
          attributes: [],
          model: classifyInfo,
        },
        {
          attributes: [],
          model: userinfo,
        },
      ],
    });
    reData.rows.map((item) => {
      item["coverUrl"] =getImgUrl(item.cover);
    });
    return reData;
  } catch (error) {
    return error;
  }
};

// 热门 默认6条
router.get("/hot", async (ctx) => {
  try {
    let reqQuery = ctx.request.query;
    let reData = await articleInfo.findAndCountAll({
      where: { status: 1 },
      attributes: ["id", "title", "views", "desc", "created_at"],
      order: [
        //排序 DESC ASC
        ["views", "DESC"],
      ],
      limit: reqQuery.limit ? parseInt(reqQuery.limit) : 6,
      offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 6 : 0,
    });
    ctx.success(reData);
  } catch (err) {
    ctx.fail(0, err);
  }
});

/**
 * 根据类型查询列表
 * limit 分页长度
 * page 分页
 * name 类型名字
 * */
router.get("/classifyList", async (ctx) => {
  try {
    let reqQuery = ctx.request.query;

    if (!reqQuery.id) {
      ctx.fail(0, "id不能为空");
    }
    // 先查询类型得到id
    let classifyData = await classifyInfo.findOne({
      where: {
        name_en: reqQuery.id,
      },
    });
    console.log("classifyData===>", classifyData.id);
    if (classifyData) {
      let rData = await fnGetArticleList(
        { c_id: classifyData.id, status: 1 },
        reqQuery
      );
      ctx.success(rData);
    } else {
      // 没有数据
      ctx.success({ count: 0, rows: [] });
    }
  } catch (err) {
    console.log(err);
    ctx.fail(0, err);
  }
});
// 分頁列表
/**
 * limit 分页长度
 * page 分页
 * title  模糊查询标题
 *
 */
router.get("/pageList", async (ctx) => {
  try {
    let reqQuery = ctx.request.query;
    let where = {};
    if (reqQuery.title) {
      where["title"] = {
        [Op.like]: `%${reqQuery["title"]}%`,
      };
    }
    let rData = await fnGetArticleList(where, reqQuery);
    console.log("==========", getUserId(ctx), "=========");
    ctx.success(rData);
  } catch (err) {
    console.log(err);
    ctx.fail(0, err);
  }
});

// 查询详情
router.get("/detail", async (ctx) => {
  try {
    let reqQuery = ctx.request.query;
    if (!reqQuery.id) {
      ctx.fail(0, "id不能为空");
    }
    let cardData = await articleInfo.findOne({
      where: {
        id: reqQuery.id,
      },
    });

    if (cardData) {
      // 查询详情的时候浏览量+1
      let newShow = cardData.views + 1;
      let requestData = await articleInfo.update(
        {
          views: newShow,
        },
        {
          where: {
            id: reqQuery.id,
          },
        }
      );
      cardData.dataValues["coverUrl"] = getImgUrl(cardData.dataValues.cover);
      ctx.success(cardData);
    } else {
      ctx.fail(0, "内容已删除,或者不存在");
    }
  } catch (err) {
    ctx.fail(0, err);
  }
});

// ----------------------------------------后台操作 需要验证登录的

// 查询列表
router.get("/list", async (ctx) => {
  try {
    let reqQuery = ctx.request.query;
    let where = {};
    if (reqQuery.title) {
      where = {
        title: {
          [Op.like]: `%${reqQuery["title"]}%`,
        },
      };
    }
    articleInfo.hasOne(classifyInfo, { foreignKey: "id", sourceKey: "c_id" });
    let reData = await articleInfo.findAndCountAll({
      where: where,
      // attributes: [Sequelize.col('classify_model.c_name'), 'id', 'content', 'views'],
      order: [
        //排序 DESC ASC
        ["created_at", "DESC"],
      ],
      limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
      offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
      raw: true,
      include: [
        {
          attributes: [],
          model: classifyInfo,
        },
      ],
    });

    ctx.success(reData);
  } catch (err) {
    console.log(err);
    ctx.fail(0, err);
  }
});
// 编辑或者添加
router.post("/editOrAdd", async (ctx) => {
  try {
    ctx.validateBody("content").required("内容不能为空").isString().trim();
    ctx.validateBody("title").required("标题不能为空").isString().trim();
    ctx.validateBody("desc").required("简介不能为空").isString().trim();

    let userId = getUserId(ctx);
    let reqBody = ctx.request.body;
    let requestData = null;
    let msgType = "添加";
    let b = {
      content: reqBody.content,
      desc: reqBody.desc,
      title: reqBody.title,
      status: reqBody.status,
      cover: reqBody.cover,
      views: 0,
      c_id: reqBody.c_id,
      u_id: userId,
    };

    if (reqBody.id) {
      delete b.id;
      // 编辑
      requestData = await articleInfo.update(b, {
        where: {
          id: reqBody.id,
        },
      });
      msgType = "修改";
    } else {
      // 新增
      requestData = await articleInfo.create(b);
    }
    if (requestData) {
      ctx.success(msgType + "成功");
    } else {
      ctx.fail(0, msgType + "失败");
    }
  } catch (err) {
    ctx.fail(0, err && err.message);
  }
});

// 删除
router.delete("/del/:id", async (ctx) => {
  try {
    if (!ctx.params.id) {
      ctx.fail(0, "id不能为空");
    }
    let requestData = await articleInfo.destroy({
      where: {
        id: ctx.params.id,
      },
    });
    if (requestData > 0) {
      ctx.success("删除成功");
    } else {
      ctx.fail(0, "文章已删除,或者不存在");
    }
  } catch (err) {
    ctx.fail(0, err);
  }
});

module.exports = router.routes();

function getuuid() {
  let s = [];
  let hexDigits = "0123456789abcdef";
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  // s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid;
}
